<template>
  <div id="workbench">
    <div class="user-info back-image">
      <div class="avatar" @click="jumpCenter">
        <img :src="basicInfo.avatarUrl || imageUrl"></img>
      </div>
      <div class="name-time">
        <p>
          <span class="name" :class="{ 'name-8' : basicInfo.agentName.length > 5 }">{{ basicInfo.agentName }}</span>
          <span class="area">{{ basicInfo.majorRegion }}</span>
        </p>
        <p class="time" v-show="!!basicInfo.updateDataDate">数据更新时间：{{ basicInfo.updateDataDate }}</p>
      </div>
      <div class="wallet" @click="goWallet" v-if="walletShow"><i class="iconfont icon-qianbao"></i> 钱包</div>
    </div>
    <div class="data-count">
      <div class="tip-info">
        <overlay :zIndex="100" :visible="isFiexd" :customStyle="{ background: 'transparent'}" @click="handleOverlay" />
        <div class="flexd-tip" @click.stop v-show="isFiexd" :style="{ top: top }">
          <span class="clear-icon"><van-icon name="clear" /></span>
          <p>{{ selectText }}</p>
        </div>
      </div>
      <div class="count-type" v-for="(item, index) in dataType" :key="item.value" @click="handleJump(item)">
        <div>
          <p class="tip">历史总数 {{ item.totalCount }}</p>
          <p class="value" :class="`color-${item.trend}`">
            <span class="num" :class="{ 'num-26' : isBigScreen }"> {{ item.todayCount }}
              <!-- <countTo :startVal='0' :endVal='item.todayCount' :duration='duration'></countTo> -->
            </span>
            <span class="text">今日新增</span>
            <span class="icon-trend">
              <i v-if="item.trend === 0">--</i>
              <i v-else-if="item.trend === 1" class="iconfont icon-shouye-shangsheng"></i>
              <i v-else class="iconfont icon-shouye-xiajiang"></i>
            </span>
          </p>
          <p class="name">
            <span>{{ item.name }}</span>
            <van-icon @click.stop="tipVisible(item, index)" name="info" :color="item.select ? '#007AE6' : '#CED1D6' " />
          </p>
        </div>
      </div>
    </div>
    <div class="my-workbench">
      <div class="title">我的工作台</div>
      <!-- <div class="title-image back-image" :style="{ backgroundImage: `url(${titleImage})` }"></div> -->
      <ul class="moduleList">
        <li class="module" v-for="(item, index) in moduleList" :key="index"
        :class="item.class" @click="handleJump(item)">
          <div class="box-center">
            <div class="message" v-if="item.value">
              <MessageTips slot="extra" :news="basicInfo[item.value]" />
            </div>
            <!-- <span class="back-image icon-box w-40" :style="{ backgroundImage: `url(${item.imageUrl})` }"></span> -->
            <span class="back-image icon-box">
              <svg class="icon-svg" aria-hidden="true">
                <use :xlink:href="`#icon-${item.icon}`"></use>
              </svg>
            </span>
            <span class="name">{{ item.name }}</span>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { Overlay } from 'vant';
import dynamicsService from 'SERVICE/dynamicsService'
import userService from 'SERVICE/userService'
import MessageTips from '@/components/MessageTips'
import { mapGetters } from 'vuex'
import countTo from 'vue-count-to'
const imageUrl = require('IMG/custom/placeholder-header-img.png')
const backImage = require('IMG/dynamics/backImage.png')
const titleImage = require('IMG/dynamics/title.png')

const dataType = [
  { trend: 0, value: 'shareTimesDataVo', todayCount: 0, totalCount: 0, yesterdayCount: 0, select: false, name: '分享次数', href: '/dynamics/articleShareList' },
  { trend: 0, value: 'customerScanArticleDataVo', query: 'articleCustomerDataVo', todayCount: 0, totalCount: 0, yesterdayCount: 0, select: false, name: '文章浏览量', href: '/dynamics/browse' },
  { trend: 0, value: 'strangerDataVo', query: 'strangerDataVo', todayCount: 0, totalCount: 0, yesterdayCount: 0, select: false, name: '访客总数', href: '/dynamics/thread' },
  { trend: 0, value: 'customerDataVo', query: 'customerDataVo', todayCount: 0, totalCount: 0, yesterdayCount: 0, select: false, name: '意向客户', href: '/custom/classify?type=2' },
  { trend: 0, value: 'customerWithMobileDataVo', query: 'customerWithMobileDataVo',  todayCount: 0, totalCount: 0, yesterdayCount: 0, select: false, name: '留电客户', href: '/custom/classify?type=3' },
  { trend: 0, value: 'communicateCustomerTimesDataVo', query: 'communicateCustomerDataVo', todayCount: 0, totalCount: 0, yesterdayCount: 0, select: false, name: '互动数量', href: '/dynamics/interact' }
]
// (index+1) % 3 ? 'box-shadow-1px-bottom-right' : 'box-shadow-1px-bottom'
const moduleList = [
  { imageUrl: require("@/assets/img/dynamics/building.png"), class: "box-shadow-1px-bottom-right", icon: 'shouye_loupan', name: '楼盘', href: '/market', id: 'loupan' },
  { imageUrl: require("@/assets/img/dynamics/write.png"), class: "box-shadow-1px-bottom-right", icon: 'shouye_xieyixie', name: '写一写', href: '/discover/newlyAdded' },
  { imageUrl: require("@/assets/img/dynamics/card.png"), class: "box-shadow-1px-bottom", icon: 'shouye_mingpian', name: '名片', href: '/user/share-card' },
  { imageUrl: require("@/assets/img/dynamics/custom.png"), class: "box-shadow-1px-bottom-right", icon: 'shouye_kehu', name: '客户', href: '/custom/group' },
  { imageUrl: require("@/assets/img/dynamics/dynamic.png"), class: "box-shadow-1px-bottom-right", icon: 'shouye_dongtai', value: 'unreadDynamicCount', name: '动态', href: '/dynamics/activityTrack' },
  { imageUrl: require("@/assets/img/dynamics/news.png"), class: "box-shadow-1px-bottom", icon: 'shouye-xiaoxi', value: 'unreadMessageCount', name: '消息', href: '/dynamics/message/messageList' },
  { imageUrl: require("@/assets/img/dynamics/date.png"), class: "box-shadow-1px-right", icon: 'shouye-shuju', name: '数据', href: '/dynamics/dataCount' },
  { imageUrl: require("@/assets/img/dynamics/invite.png"), class: "box-shadow-1px-right", icon: 'shouye_yaoqing', name: '邀请', href: '/user/invitation/awWelfare' },
  { imageUrl: require("@/assets/img/dynamics/my.png"), class: "", icon: 'shouye_wode', name: '我的', href: '/user' }
]

import wechatService from 'SERVICE/wechatService'
export default {
  data() {
    return {
      dataType,
      imageUrl,
      backImage,
      titleImage,
      selectText: '',
      moduleList,
      isFiexd: false,
      basicInfo: {
        agentName: ''
      },
      isBigScreen: false,
      walletShow: false,
      duration: 2000,
      top: '',
      showInvite: false
    }
  },
  components: {
    Overlay,
    countTo,
    MessageTips
  },
  created() {
    // 未登录直接跳转预览页
    if (!(this.userInfo && this.userInfo.token)) {
      return this.$router.replace('/preview')
    }
    this.walletShow = !!this.userInfo.selfSupport
    this.dynamicsData()
    this.showCompanyTips()
    this.getInvitationActivity()
    this.isBigScreen = document.body.clientWidth >= 400
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    // 是否邀请有礼
    getInvitationActivity() {
      wechatService
        .getInvitationActivity({})
        .then(res => {
          this.showInvite = res.invitationActivity
        })
        .catch()
    },
    setMajorRegion(str) {
      let majorRegion = str.split("/")[1]
      majorRegion = majorRegion.replace("市", "")
      majorRegion = majorRegion.replace("区", "")
      return majorRegion
    },
    dynamicsData() {
      dynamicsService.getDynamicsCollect().then(res => {
        let { agentName, avatarUrl, majorRegion, updateDataDate, unreadDynamicCount, unreadMessageCount } = res
        if(majorRegion) majorRegion = this.setMajorRegion(majorRegion)
        this.basicInfo = { agentName, avatarUrl, majorRegion, updateDataDate, unreadDynamicCount, unreadMessageCount }
        // trend字段表示的是今天昨天的一个对比
        // 0 表示今天增长与昨天相同   1 表示今天上升  2 表示今天下降
        this.dataType.forEach((item,index) => {
          let obj = res[item.value]
          let trend = ''
          if (obj.todayCount === obj.yesterdayCount) {
            trend = 0
          } else if (obj.todayCount > obj.yesterdayCount) {
            trend = 1
          } else {
            trend = 2
          }
          // trend = index % 3
          item.params = res[item.query] || {}
          obj.trend = trend
          item = Object.assign(item, obj)
        })
        // console.log(this.dataType)
      }, err => {
        console.log(err)
      });
    },
    jumpCenter() {
      this.$router.push('/user/edit')
    },
    handleOverlay() {
      this.isFiexd = false
      this.dataType.forEach(list => {
        if (list.select) list.select = false
      })
    },
    getInnerText(index) {
      let params = {
        0: '您分享的楼盘、名片、文章次数的总和',
        1: '客户浏览您写一写文章的次数总和',
        2: '客户浏览您写一写文章和小程序文章的人数总和',
        3: '客户浏览您楼盘、名片、留电和您手动置为客户的人数总和',
        4: '客户首次授权电话和您手动添加客户电话号码的人数总和',
        5: '您或者客户主动发起聊天/打电话的次数总和'
      }
      return params[index]
    },
    tipVisible(item, index) {
      let ev = event || window.event
      let pos = ev.target.getBoundingClientRect()
      let { x, y } = pos
      let max = document.body.clientWidth
      item.select = true
      this.selectText = this.getInnerText(index)
      // x = x + 15
      y = y + 25
      // if (item.align === 'left') {
      //   this.pos = { left: x +'px', top: y + 'px' }
      // } else if(item.align === 'right') {
      //   this.pos = { right: max - x +'px', top: y + 'px' }
      // } else {
      //   this.pos = { left: x/3 +'px', top: y + 'px' }
      // }
      this.top = y + 'px'
      this.isFiexd = true
    },
    handleJump(item) {
      //如用户在审核通过后，第一次进入“楼盘”功能时，则传递参数过去用于弹出引导
      const companyApproveState = window.localStorage.getItem('company-approve-state');
      if(item.id == 'loupan' && companyApproveState == 1){
        window.localStorage.setItem('company-approve-state', 2)
        return this.$router.push({ path: item.href, query: {
          ...this.$route.query,
          showGuide: true
        }})
      }
      // 邀请有礼
      if (item.name === '邀请') {
        let url = this.showInvite ? '/wx/invite/activity' : '/wx/invite/friends'
        return this.$router.push(url)
      }
      // 点击有消息提醒的功能进行消息提示清除
      if(item.value && this.basicInfo[item.value]) {
        this.updateUnReadMessageCount(item)
      }
      this.$router.push({ path: item.href, query: item.params})
    },
    async updateUnReadMessageCount(item) {
      try {
        if (item.value === 'unreadMessageCount') {
          await dynamicsService.updateUnReadMessageCount()
        } else {
          await dynamicsService.updateDataCenterInfo()
        }
          
      } catch (error) {
        
      }
    },
    // 经纪人未加入经纪公司时进行提示
    async showCompanyTips(){
      try {
        const response = await userService.getOrganizationAudit()
        //  需要进行提醒
        const { organizationName, auditType, unorganizedGuide, organizationId, remind }  = response;

        if(remind == 0 && this.userInfo.selfSupport){
          // 没有加入经纪公司

          if((auditType == 3 || auditType == 4) && unorganizedGuide == 0){
             //调用 “更新提示” 的接口
            this.updateUserExpandOrganized()
          }

          if(auditType == 3){
            this.$dialog.confirm({
              title: '提示',
              message: '您尚未加入任何经纪公司，赶紧去加入吧〜',
              cancelButtonText: '取消',
              confirmButtonText: '去加入'
            }).then(_=> this.$router.push('/user/edit?guide=1'));
          }

          //审核通过
          if(auditType == 1){
            this.$dialog.confirm({
              title: '审核通过',
              message: '恭喜您！已成功加入经纪公司啦〜',
              confirmButtonText: '我知道了',
              showCancelButton: false
            }).then(_ => {
              // this.$router.push('/market?showGuide=true')
              window.localStorage.setItem('company-approve-state', 1)
            });
          }

          //审核失败
          if(auditType == 2){
            this.$dialog.confirm({
              title: '审核失败',
              className: 'company-approve-failure',
              message: '您加入经纪公司的申请，审核失败！',
              cancelButtonText: '我知道了',
              confirmButtonText: '重新提交'
            }).then(_=> this.$router.push(`/user/edit/userBrokerCompany?id=${organizationId}`))
          }

          //经纪公司被删除
          if(auditType == 4){
            this.$dialog.confirm({
              title: '提示',
              className: 'company-approve-failure',
              message: `【${organizationName}】 已将您删除，请在 “我的-个人资料” 页，选择经纪公司重新提交申请`,
              cancelButtonText: '我知道了',
              confirmButtonText: '重新提交'
            }).then(_=> this.$router.push(`/user/edit/userBrokerCompany?id=${organizationId}`))
          }

          // 后台加入经纪公司
          if(auditType == 5){
            this.$dialog.confirm({
              title: '提示',
              message: `【${organizationName}】 已将您加入啦~`,
              confirmButtonText: '我知道了',
              showCancelButton: false
            }).then(_ => {});
          }

          // 审核48消失过期失效
          if(auditType == 6){
            this.$dialog.confirm({
              title: '申请失效',
              className: 'company-approve-failure',
              message: `很遗憾！您加入经纪公司的申请，由于超过24小时未得到审核，已失效了~`,
              cancelButtonText: '我知道了',
              confirmButtonText: '重新提交'
            }).then(_=> this.$router.push(`/user/edit/userBrokerCompany?id=${organizationId}`))
          }
        }
      } catch (error) {}
    },
    //更新经纪人未加入和审核通过公司指引显示标志位 指引类型 1-未加入公司 2-公司审核通过
    async updateUserExpandOrganized(){
      userService.updateUserExpandOrganized()
    },
    // 浏览器回退监听
    // goBack () {
    //   setTimeout(()=>{WeixinJSBridge.call("closeWindow")}, 100);  
    //   wx.closeWindow()
    //   console.log("点击了返回",wx);
    // },
    goWallet () {
      this.$router.push('/money/wallet')
    }
  },
  mounted() {
    wx.hideOptionMenu();
    // if (window.history && window.history.pushState) {
    //    var state = {
    //     title: "title",
    //     url: "#"
    //   };
    //   window.history.pushState(state, "title", "#");
    history.pushState(null, null, document.URL)
    // window.addEventListener('popstate', this.goBack, false)
      // window.addEventListener('popstate', this.goBack, false);
    // }
  },
  destroyed() {
    // window.removeEventListener('popstate', this.goBack,false)
  }
}
</script>

<style lang="less" scoped>
.user-info {
  width: 100%;
  height: 124px;
  background: #0062AC;
  display: flex;
  // justify-content: space-between;
  align-items: center;
  padding: 0 0 0 24px;
  .name-time {
    color: #fff;
    padding-left: 16px;
    font-size: 0;
    flex: 1;
    .name {
      font-size: 26px;
      height: 32px;
      line-height: 32px;
      font-weight: bold;
      max-width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      display: inline-block;
      // float: left;
      vertical-align: text-bottom;
    }
    
    .name-8 {
      font-size: 20px;
    }
    .area {
      font-size: 12px;
      height: 18px;
      line-height: 18px;
      padding-left: 5px;
      display: inline-block;
      margin-bottom: 2px;
      // border-bottom: 1px solid transparent;
      vertical-align: text-bottom;
    }
    .time {
      display: block;
      font-size: 12px;
      height: 22px;
      line-height: 22px;
      padding-top: 3px;
      // font-weight: 200;
    }
  }
  .avatar {
    width: 60px;
    height: 60px;
    img {
      border-radius: 50%;
      border: 2px solid #fff;
    }
  }
  .wallet{
    font-size: 12px;
    color:rgba(64,81,112,1);
    width: 66px;
    height: 36px;
    background-color: #fff;
    border-top-left-radius: 19px;
    border-bottom-left-radius: 19px;
    display: flex;
    align-items: center;
    justify-content: center;
    i{
      color: #E4AF67;
      margin-right:2px ;
      font-size: 20px;
    }
  }
}
.data-count {
  padding-bottom: 20px;
  border-bottom: 12px solid #F2F6F7;
  .flexd-tip {
    max-width: 250px;
    padding: 8px 20px 8px 10px;
    border-radius: 8px;
    position: fixed;
    left: 75px;
    background: rgba(0, 0, 0, 0.65);
    z-index: 1;
    font-size: 12px;
    line-height: 20px;
    color: #fff;
    .clear-icon {
      width: 12px;
      height: 12px;
      display: inline-block;
      position: absolute;
      top: 2px;
      right: 3px;
      &:active, &:hover {
        color: #E65E2E;
      }
    }
  }
  .left {
    padding-left: 24px;
  }
  .center{
    justify-content: center;
  }
  .right {
    padding-right: 24px;
    justify-content: flex-end;
  }
  .count-type {
    width: 33.3%;
    margin-top: 24px;
    padding-left: 16px;
    display: inline-flex;
    height: 68px;
    .tip {
      // height: 12px;
      font-size: 10px;
      // line-height: 12px;
      color: #9CA5B5;
    }
    .name {
      font-size: 12px;
      color: #405170;
      padding-top: 4px;
      height: 20px;
      span {
        font-weight: bold;
      }
      i {
        padding-left: 4px;
        vertical-align: top;
      }
    }
    .color-0 {
      color: #405170;
    }
    .color-2 {
      color: #28B324;
    }
    .color-1 {
      color: #E65E2E;
    }
    .value {
      height: 32px;
      line-height: 32px;
      font-size: 0;
      .num {
        font-size: 22px;
      }
      .num-26 {
        font-size: 26px;
      }
      .text {
        color: #9BA4B4;
        font-size: 10px;
        margin-left: -6px;
      }
      .icon-trend {
        i {
          font-size: 10px;
          padding-left: 4px;
        }
      }
    }
  }
}

.back-image {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

.my-workbench {
  .title {
    color: #13284D;
    height: 26px;
    font-size: 18px;
    font-weight: bold;
    line-height: 26px;
    margin: 16px 0 4px 24px;
  }
  .title-image {
    height: 58px;
    width: 248px;
    margin: 0 auto;
    margin-top: 8px;
  }
  .moduleList {
    padding: 8px 16px;
    padding-top: 4px;
    .module {
      width: 33.3%;
      height: 114px;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      // margin-right: 1px;
      // margin-bottom: 1px;
      .box-center {
        text-align: center;
        position: relative;
        font-size: 0px;
        .message {
          transform: scale(0.9);
          position: absolute;
          top: -5px;
          right: -3px;
        }
        .icon-box {
          width: 32px;
          height: 32px;
          display: block;
          margin: 0 auto;
        }
        .w-40 {
          width: 40px;
          height: 40px;
        }
        .name {
          color: #333;
          font-size: 0.32rem;
          margin-top: 8px;
          display: inline-block;
          line-height: 16px;
          font-size: 12px;
        }
      }
      &:active {
        background: #eee;
      }
    }
  }
  .icon-svg {
    width: 32px; height: 32px;
    // vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
}

</style>

<style lang="less">
.company-approve-failure.van-dialog{
  .van-dialog__header{
    font-size:18px;
    font-weight:600;
    color:rgba(234,77,46,1);
  }
}
</style>